package rd.hardcore.engine.sample {
	import rd.hardcore.events.SampleSourceEvent;
	import rd.hardcore.engine.sample.source.SampleSource;

	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.SampleDataEvent;
	import flash.media.Sound;
	import flash.utils.ByteArray;

	/**
	 * 
	 * @see Event#COMPLETE
	 */[Event( name = "complete", type = "Event" )]
	
	/**
	 * @author plepers
	 */
	public class Sample extends EventDispatcher{
		
		private static const _BUFF : int = 8*2048;

		public function Sample ( source : SampleSource ) {
			_source = source;
			_sampleDatas = source.getDatas();
			
			_build();
		}

		public function play () : void {
			trace( "sample play");
			if( _source.extracted )
				_sound.play();
			else
				_source.addEventListener( SampleSourceEvent.EXTRACTED, _sourceExracted );
		}

		public function stop () : void {
			_source.removeEventListener( SampleSourceEvent.EXTRACTED, _sourceExracted );
		}

		public function dispose () : void {
			_sampleDatas = null;
		}


		private function _build () : void {
			_sound = new Sound( );
			_sound.addEventListener( SampleDataEvent.SAMPLE_DATA, sampleData );
			
			_pos = _sampleDatas.startPos;
		}

		private function sampleData (event : SampleDataEvent) : void {
			//if( ! _source.extracted ) return;
			
			
			var raw : ByteArray = _sampleDatas.rawDatas;
			var l : int = Math.min( _BUFF, _sampleDatas.endPos - _pos );
			
			var buff : ByteArray = new ByteArray();
			buff.writeBytes( raw, _pos, l );
			
			event.data.writeBytes( buff );
			//buff.position = 0;

//			for ( var c:int=0; c<2048; c++ ) {
//     		   event.data.writeFloat( buff.readFloat() );
//     		   //trace( buff.readFloat() );
//				event.data.writeFloat(Math.sin((Number(c+event.position)/Math.PI/2))*0.25);
//  			  }
			_pos += l;
			
			
			if( _pos >= _sampleDatas.endPos ) {
				_complete();
			}
		}

		private function _sourceExracted (event : SampleSourceEvent) : void {
			trace( "source extracted ");
			_sound.play();
		}

		private function _complete () : void {
			trace( "rd.hardcore.engine.sample.Sample - _complete -- ", _pos );
			dispatchEvent( new Event( Event.COMPLETE ) );
		}

		
		private var _sound : Sound;
		
		private var _sampleDatas : SampleDatas;

		private var _source : SampleSource;
		
		private var _pos : uint;

	}
}
